/**
 * 产品列表
 */
import { query, create, remove, update } from '../services/product';
import { isSuccess } from '../configs/error';
import createModel from './base';

export default createModel({
	namespace: 'productList',

	state: {
    list: [],
		permissionIds: []
	},

	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
        dispatch({
          type: 'query'
        });
				// if (location.pathname === '/productList') { // 每次刷新一下，获取最新
				// 	dispatch({
				// 		type: 'query'
				// 	});
				// }
			});
		},
	},

	effects: {
		*query({ payload = {}, resetSelectedRowKeys = false }, { call, put, select }) {
			if (payload && payload.current) {
				yield put({
					type: 'set',
					payload: {
						page: payload.current
					}
				});
			}
			const data = yield call(query, payload);
			if (isSuccess(data)) {
				const resultData = data.data;
				const products = resultData.records;
				yield put({
					type: 'set',
					payload: {
						...resetSelectedRowKeys ? { selectedRowKeys: [] } : null,
						list: products,
						total: resultData.total,
						pageSize: resultData.size,
						current: resultData.current,
					},
				});
				const { productId } = yield select(s => s.app);
				if (!productId && products && products.length) yield put({ type: 'app/set', productId: products[0].id });
			}
		},
	},
	reducers: {},
}, query, create, remove, update);
